package cn.dzhang.mybatis.repository;

import java.util.List;

import cn.dzhang.mybatis.model.User;
import cn.dzhang.mybatis.model.UserMapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class UserRespository
{

	private static SqlSession session;

	@Test
	public void testGetUser() throws Exception
	{
		UserMapper mapper = session.getMapper(UserMapper.class);
		User user = mapper.findById(1);
		System.out.println(user);
	}

	@Test
	public void testGetUsers() throws Exception
	{
		UserMapper mapper = session.getMapper(UserMapper.class);
		List<User> users = mapper.findByUsername("dzhang");
		System.out.println(users);
	}

	@Test
	public void testFindById_xml() throws Exception
	{
		User user = session.selectOne(UserOperation.findById, 1);
		System.err.println(user);
	}

	@Test
	public void testFindAllExpiredUsers_XML() throws Exception
	{
		List<User> users = session.selectList(UserOperation.findAllExpired);
		System.err.println(users);
	}

	@Test
	public void testUpdate() throws Exception
	{
		User user = session.selectOne(UserOperation.findById, 6);
		user.setName("虚竹");
		int cnt = session.update(UserOperation.update, user);
		Assert.assertEquals(1, cnt);
	}

	@Test
	public void testDeleteById() throws Exception
	{
		int cnt = session.delete(UserOperation.deleteById, 9);
		Assert.assertEquals(1, cnt);
	}

	@Test
	public void testSave() throws Exception
	{
		User user = new User();
		user.setName("梦之旅");
		user.setUsername("travel");
		user.setPassword("kingdom");
		user.setExpired(true);
		user.setOnline(false);

		int cnt = session.insert(UserOperation.save, user);
		Assert.assertEquals(1, cnt);
	}

	@Test
	public void testFindAllExpiredUsers() throws Exception
	{
		UserMapper mapper = session.getMapper(UserMapper.class);
		List<User> users = mapper.findAllExpired();
		System.out.println(users);
	}

	@BeforeClass
	public static void setup() throws Exception
	{
		SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
		SqlSessionFactory sessionFactory = sessionFactoryBuilder
		        .build(Resources.getResourceAsReader("configuration.xml"));
		session = sessionFactory.openSession(false);
	}

	@Before
	public void begin() throws Exception
	{
	}

	@After
	public void commit() throws Exception
	{
		session.commit();
	}

	@AfterClass
	public static void destroy() throws Exception
	{
		session.close();
	}

}
